package com.yituo.mjworld.mvc.action.admin;

import com.alibaba.fastjson.JSONObject;
import com.yituo.mjworld.core.annotation.NoToken;
import com.yituo.mjworld.core.annotation.Rule;
import com.yituo.mjworld.mvc.service.other.QiniuConfig;
import com.yituo.mjworld.core.web.core.MyHttpRequest;
import com.yituo.mjworld.core.web.core.MyHttpResponse;
import com.yituo.mjworld.mvc.service.impl.QiniuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 七牛模块.
 */
@Component
public class QiniuAction {
  @Autowired
  QiniuServiceImpl qiniuService;

  /**
   * 删除七牛图片
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @Rule(name = "url", name_zn = "欲删除的URL")
  public void delete(MyHttpRequest req, MyHttpResponse res) throws IOException {
    String url = req.getParameter("url");
    boolean result = qiniuService.delete(qiniuService.getFileNameForUrl(url));
    if (result) {
      res.success("删除成功!");
    } else {
      res.failed("删除失败!");
    }
  }

  /**
   * 获取七牛的上传凭证token
   *
   * @param req
   * @param res
   * @throws IOException
   */
  @NoToken
  public void getToken(MyHttpRequest req, MyHttpResponse res) throws IOException {
    String fileType = req.getParameter("fileType");
    Map<String, String> typeMap = new HashMap<String, String>();
    typeMap.put("image/png", ".png");
    typeMap.put("image/jpeg", ".jpeg");
    typeMap.put("image/jpg", ".jpg");
    if (!StringUtils.isEmpty(fileType) && !StringUtils.isEmpty(typeMap.get(fileType))) {
      JSONObject json = new JSONObject();
      json.put("token", qiniuService.getToken(typeMap.get(fileType)));
      json.put("domain", QiniuConfig.delta2017.DOMAIN);
      res.success(json);
      return;
    }
    res.failedFor302("文件类型不能为空!");
  }
}
